<?php

namespace App\Admin\Grid\Tools;

use App\Admin\Grid;
use Illuminate\Pagination\LengthAwarePaginator;

class Paginator extends AbstractTool
{
    /**
     * laravel分页器
     *
     * @var \Illuminate\Pagination\LengthAwarePaginator
     */
    protected $paginator = null;

    /**
     * Create a new Paginator instance.
     *
     * @param Grid $grid
     */
    public function __construct(Grid $grid)
    {
        $this->grid = $grid;

        $this->initPaginator();
    }

    /**
     * 初始化分页
     *
     * @return void
     */
    protected function initPaginator()
    {
        $this->paginator = $this->grid->model()->eloquent();

        if ($this->paginator instanceof LengthAwarePaginator) {
            $this->paginator->appends(\Request::all());

            LengthAwarePaginator::defaultView('admin.pagination.layui');
        }
    }

    /**
     * 获取分页的链接
     *
     * @return string
     */
    protected function paginationLinks()
    {
        return $this->paginator->render(null, [
            'perPages' => $this->grid->perPages,
        ])->toHtml();
    }

    /**
     * Render Paginator.
     *
     * @return string
     */
    public function render()
    {
        if (!$this->grid->usePagination()) {
            return '';
        }

        return $this->paginationLinks();
    }
}
